package com.ssy.lingxi.platform.manage.serviceimpl.content;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.content.ContentInformation;
import com.ssy.lingxi.platform.manage.entity.content.ContentLabel;
import com.ssy.lingxi.platform.manage.entity.content.QContentLabel;
import com.ssy.lingxi.platform.manage.model.request.common.CommonIdRequest;
import com.ssy.lingxi.platform.manage.model.request.common.CommonStatusRequest;
import com.ssy.lingxi.platform.manage.model.request.content.ContentLabelPageRequest;
import com.ssy.lingxi.platform.manage.model.request.content.ContentLabelRequest;
import com.ssy.lingxi.platform.manage.repository.ContentInformationRepository;
import com.ssy.lingxi.platform.manage.repository.ContentLabelRepository;
import com.ssy.lingxi.platform.manage.service.content.IContentLabelService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签管理 - 业务实现层
 * @author fhj
 * @version 2.0.0
 * @date 2020/9/18
 */
@Service
public class ContentLabelServiceImpl implements IContentLabelService {

    @Resource
    private ContentLabelRepository contentLabelRepository;
    @Resource
    private ContentInformationRepository contentInformationRepository;
    @Resource
    private JPAQueryFactory jpaQueryFactory;

    @Override
    @ApiOperation(value = "列表")
    public Wrapper<PageData<ContentLabel>> page(ContentLabelPageRequest request) {
        QContentLabel qContentLabel = QContentLabel.contentLabel;
        JPAQuery<ContentLabel> jpaQuery = jpaQueryFactory.select(qContentLabel).from(qContentLabel);
        if(StringUtils.isNotBlank(request.getName())) {
            jpaQuery.where(qContentLabel.name.contains(request.getName()));
        }
        long totalCount = jpaQuery.fetchCount();
        List<ContentLabel> list = jpaQuery.orderBy(qContentLabel.createTime.desc()).limit(request.getPageSize()).offset((long) (request.getCurrent() - 1) * request.getPageSize()).fetch();
        return Wrapper.success(new PageData<>(totalCount, list));
    }

    @Override
    @ApiOperation(value = "详情")
    public Wrapper<ContentLabel> get(CommonIdRequest request) {
        ContentLabel contentLabel = contentLabelRepository.findById(request.getId()).orElse(null);
        if(contentLabel == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        return Wrapper.success(contentLabel);
    }

    @Override
    @Transactional
    @ApiOperation(value = "新增")
    public Wrapper<Void> add(ContentLabelRequest request, UserLoginCacheDTO user) {
        ContentLabel contentLabel = new ContentLabel();
        BeanUtils.copyProperties(request, contentLabel);
        contentLabelRepository.saveAndFlush(contentLabel);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "修改")
    public Wrapper<Void> update(ContentLabelRequest request, UserLoginCacheDTO user) {
        ContentLabel contentLabel = contentLabelRepository.findById(request.getId()).orElse(null);
        if(contentLabel == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if(contentLabel.getStatus().equals(CommonBooleanEnum.YES.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        BeanUtils.copyProperties(request, contentLabel);
        contentLabelRepository.saveAndFlush(contentLabel);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "停用/启用")
    public Wrapper<Void> updateStatus(CommonStatusRequest request, UserLoginCacheDTO user) {
        //停用标签时, 需要先判断该标签是否被资讯信息所关联, 如果有则不能被停用
        if(request.getEnableStatus().equals(CommonBooleanEnum.NO.getCode())) {
            List<ContentInformation> all = contentInformationRepository.findAll();
            if(CollectionUtil.isNotEmpty(all)) {
                if(all.stream().anyMatch(a -> a.getLabelIds().contains(request.getId()))) {
                    throw new BusinessException(ResponseCode.MAN_DATA_RELATION_INFORMATION);
                }
            }
        }

        ContentLabel contentLabel = contentLabelRepository.findById(request.getId()).orElse(null);
        if(contentLabel == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        contentLabel.setStatus(request.getEnableStatus());
        contentLabelRepository.saveAndFlush(contentLabel);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "删除")
    public Wrapper<Void> delete(CommonIdRequest request, UserLoginCacheDTO user) {
        //删除标签时, 需要先判断该标签是否被资讯信息所关联, 如果有则不能被停用
        List<ContentInformation> all = contentInformationRepository.findAll();
        if(CollectionUtil.isNotEmpty(all)) {
            if(all.stream().anyMatch(a -> a.getLabelIds().contains(request.getId()))) {
                throw new BusinessException(ResponseCode.MAN_DATA_RELATION_INFORMATION);
            }
        }

        ContentLabel contentLabel = contentLabelRepository.findById(request.getId()).orElse(null);
        if(contentLabel == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if(contentLabel.getStatus().equals(CommonBooleanEnum.YES.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        contentLabelRepository.delete(contentLabel);
        return Wrapper.success();
    }

    @Override
    @ApiOperation(value = "所有")
    public Wrapper<List<ContentLabel>> all() {
        List<ContentLabel> contentLabelList = contentLabelRepository.findAllByStatus(CommonBooleanEnum.YES.getCode(), Sort.by("id"));
        return Wrapper.success(contentLabelList);
    }

    @Override
    @ApiOperation(value = "热门标签")
    public Wrapper<List<ContentLabel>> hot() {
        //获取所有可用的标签, 再获取所有资讯, 筛选出有包含在资讯的标签
        List<ContentLabel> contentLabelList = contentLabelRepository.findAllByStatus(EnableDisableStatus.ENABLE.getCode(), Sort.by(Sort.Direction.DESC,"createTime"));
        contentLabelList = contentLabelList.stream()
                .filter(a -> contentInformationRepository.findAll().stream().anyMatch(b -> b.getLabelIds().contains(a.getId())))
                .collect(Collectors.toList());
        return Wrapper.success(contentLabelList);
    }
}
